package com.zhifei.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhifei.common.utils.DateUtils;
import com.zhifei.common.utils.Result;
import com.zhifei.common.utils.StringUtils;
import com.zhifei.system.domain.EmployeeMonthEntity;
import com.zhifei.system.service.EmployeeMonthService;
import com.zhifei.system.service.EmployeeService;
import com.zhifei.system.service.JdService;
import com.zhifei.system.util.jd.JdOtherApOrderVo;
import kingdee.bos.webapi.client.K3CloudApiClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class JdServiceImpl implements JdService {

    @Autowired
    private EmployeeMonthService employeeMonthService;
    @Autowired
    private EmployeeService employeeService;

    @Override
    public void addK3cloudMaterial(String userId,String userName,String userMobile,String k3cloudPositionId,String k3cloudRankId,String monthPay,String quoteMonthPay){
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("IsAutoSubmitAndAudit", "true");
            k3CloudObj.put("IsAutoAdjustField", "true");
            JSONObject materialK3CloudObj = new JSONObject();
            materialK3CloudObj.put("FCreateOrgId",this.FNumber("100"));
            materialK3CloudObj.put("FUseOrgId",this.FNumber("100"));
            materialK3CloudObj.put("FNumber",userId);
            materialK3CloudObj.put("FName",userName);
            materialK3CloudObj.put("FSpecification",userMobile);
            materialK3CloudObj.put("FMaterialGroup",this.FNumber("6"));
            materialK3CloudObj.put("F_ora_GW",this.FNumber(k3cloudPositionId));
            materialK3CloudObj.put("F_ora_ZJ",this.FNumber(k3cloudRankId));
            materialK3CloudObj.put("F_ZF_BJYX",quoteMonthPay);
            materialK3CloudObj.put("F_ZF_YXCB",monthPay);
            JSONObject materialSubK3CloudObj = new JSONObject();
            materialSubK3CloudObj.put("FErpClsID","6");
            materialSubK3CloudObj.put("FFeatureItem","1");
            materialK3CloudObj.put("FCategoryID",this.FNumber("008"));
            materialK3CloudObj.put("FTaxType",this.FNumber("WLDSFL01_SYS"));
            materialK3CloudObj.put("FTaxRateId",this.FNumber("SL02_SYS"));
            materialK3CloudObj.put("FBaseUnitId",this.FNumber("ZF01"));
            materialK3CloudObj.put("FWEIGHTUNITID",this.FNumber("kg"));
            materialK3CloudObj.put("FVOLUMEUNITID",this.FNumber("m"));
            materialK3CloudObj.put("SubHeadEntity",materialK3CloudObj);
            k3CloudObj.put("Model",materialK3CloudObj);
            String params = JSONObject.toJSONString(k3CloudObj);
            System.out.println("推送金蝶物料传参："+params);
            String addMaterialResult = k3CloudApiClient.save("BD_MATERIAL", params);
            JSONObject k3CloudResultJson = JSON.parseObject(addMaterialResult);
            JSONObject allocateObj = new JSONObject();
            allocateObj.put("IsAutoAdjustField", "true");
            allocateObj.put("IsAutoSubmitAndAudit", "true");
            allocateObj.put("PkIds",JSON.parseObject(k3CloudResultJson.getString("Result")).getString("Id"));
            allocateObj.put("TOrgIds","1,100169,100170,109555");
            k3CloudApiClient.excuteOperation("BD_MATERIAL","Allocate",JSONObject.toJSONString(allocateObj));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void addK3cloudVendor(String vendorNumber,String vendorName,String bankAccount,String venBankNumberName,String bankOperatorNumber,String bankOpeningBank){
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("IsAutoSubmitAndAudit", "true");
            k3CloudObj.put("IsAutoAdjustField", "true");
            JSONObject vendorK3CloudObj = new JSONObject();
            vendorK3CloudObj.put("FSupplierId",0);
            vendorK3CloudObj.put("FCreateOrgId",this.FNumber("100"));
            vendorK3CloudObj.put("FNumber",vendorNumber);
            vendorK3CloudObj.put("FUseOrgId",this.FNumber("100"));
            vendorK3CloudObj.put("FName",vendorName);
            JSONObject fBaseInfoK3CloudObj = new JSONObject();
            fBaseInfoK3CloudObj.put("FSupplyClassify","CG");
            vendorK3CloudObj.put("FBaseInfo",fBaseInfoK3CloudObj);
            JSONObject fBusinessInfoK3CloudObj = new JSONObject();
            fBusinessInfoK3CloudObj.put("FVmiBusiness",false);
            fBusinessInfoK3CloudObj.put("FEnableSL",false);
            vendorK3CloudObj.put("FBusinessInfo",fBusinessInfoK3CloudObj);
            JSONObject fFinanceInfoK3CloudObj = new JSONObject();
            fFinanceInfoK3CloudObj.put("FPayCurrencyId",this.FNumber("PRE001"));
            fFinanceInfoK3CloudObj.put("FTaxType",this.FNumber("SFL02_SYS"));
            fFinanceInfoK3CloudObj.put("FInvoiceType","1");
            fFinanceInfoK3CloudObj.put("FTaxRateId",this.FNumber("SL02_SYS"));
            vendorK3CloudObj.put("FFinanceInfo",fFinanceInfoK3CloudObj);
            k3CloudObj.put("Model",vendorK3CloudObj);
            String params = JSONObject.toJSONString(k3CloudObj);
            System.out.println("推送金蝶供应商传参："+params);
            String addVendorResult = k3CloudApiClient.save("BD_Supplier", params);
            JSONObject k3CloudResultJson = JSON.parseObject(addVendorResult);
            JSONObject allocateObj = new JSONObject();
            allocateObj.put("IsAutoAdjustField", "true");
            allocateObj.put("IsAutoSubmitAndAudit", "true");
            allocateObj.put("PkIds",JSON.parseObject(k3CloudResultJson.getString("Result")).getString("Id"));
            allocateObj.put("TOrgIds","1,100169,100170,109555");
            k3CloudApiClient.excuteOperation("BD_Supplier","Allocate",JSONObject.toJSONString(allocateObj));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Result listOtherApOrder() {
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("FormId","AP_OtherPayable");
            k3CloudObj.put("FieldKeys","FCONTACTUNIT.FNumber,FTOTALAMOUNTFOR_H,FDATE");
//            Date preDate = DateUtils.addMonths(new Date(),-1);
//            String nowDate = DateUtils.parseDateToStr("yyyy/MM/dd",preDate);

            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            String format = sdf.format(new Date());
            int month = Integer.parseInt(format);
            String firstDayOfMonth = DateUtils.getFirstDayOfMonth(month);
            String lastDayOfMonth = DateUtils.getLastDayOfMonth(month);
            k3CloudObj.put("FilterString","FBillTypeID='00505694799c9a1111e327684fe24f72' and FDATE>='"+firstDayOfMonth+"' and FDATE<='"+lastDayOfMonth+"'");
            k3CloudObj.put("OrderString","FDATE desc");
            k3CloudObj.put("TopRowCount",0);
            k3CloudObj.put("StartRow",0);
            k3CloudObj.put("Limit",0);
            k3CloudObj.put("SubSystemId","");
            String params = JSONObject.toJSONString(k3CloudObj);
            System.out.println("金蝶其他应付单查询传参："+params);
            List<List<Object>> otherApOrderList = k3CloudApiClient.executeBillQuery(params);
            List<JdOtherApOrderVo> jdOtherApOrderVoList = new ArrayList<>();
            for(List<Object> otherApOrder : otherApOrderList){
                JdOtherApOrderVo jdOtherApOrderVo = new JdOtherApOrderVo();
                String jobNum = (String)otherApOrder.get(0);//工号
                jdOtherApOrderVo.setJobNum(jobNum);
                Double travelExpenses = (Double)otherApOrder.get(1);//差旅成本
                jdOtherApOrderVo.setTravelExpenses(travelExpenses);
                jdOtherApOrderVoList.add(jdOtherApOrderVo);
            }
            Map<String, DoubleSummaryStatistics> collectGroupByTravelExpenses = jdOtherApOrderVoList.stream().collect(Collectors.groupingBy(JdOtherApOrderVo::getJobNum, Collectors.summarizingDouble(JdOtherApOrderVo::getTravelExpenses)));
            for (String jobNum : collectGroupByTravelExpenses.keySet()) {
                Double travelExpenses = collectGroupByTravelExpenses.get(jobNum).getSum();
                employeeMonthService.caclPriceByTravelExpenses(jobNum,DateUtils.parseDateToStr("yyyy-MM",DateUtils.getFirstDayOfNowMonth()),BigDecimal.valueOf(travelExpenses));
                employeeService.caclPriceByTravelExpenses(jobNum,BigDecimal.valueOf(travelExpenses));
            }
            return Result.success(otherApOrderList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    @Override
    public Result listReceiveBill() {
        try {
            K3CloudApiClient k3CloudApiClient = login();
            JSONObject k3CloudObj = new JSONObject();
            k3CloudObj.put("FormId","AR_RECEIVEBILL");
            k3CloudObj.put("FieldKeys","FBillNo,FDATE,FSRCMATERIALID.FNumber,F_SBAY_Date,FAFTTAXTOTALAMOUNT,FREALRECAMOUNT");
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            String format = sdf.format(new Date());
            int month = Integer.parseInt(format);
            k3CloudObj.put("FilterString","FBillTypeID='36cf265bd8c3452194ed9c83ec5e73d2' and FDATE>='"+DateUtils.getFirstDayOfMonth(month)+"' and FDATE<='"+DateUtils.getLastDayOfMonth(month)+"'");
//            k3CloudObj.put("FilterString","FBillTypeID='36cf265bd8c3452194ed9c83ec5e73d2' and FDATE>='2023-01-01' and FDATE<='2023-01-31'");
            k3CloudObj.put("OrderString","FDATE desc");
            k3CloudObj.put("TopRowCount",0);
            k3CloudObj.put("StartRow",0);
            k3CloudObj.put("Limit",0);
            k3CloudObj.put("SubSystemId","");
            String params = JSONObject.toJSONString(k3CloudObj);
            System.out.println("金蝶收款单查询传参："+params);
            List<List<Object>> receiveBillOrderList = k3CloudApiClient.executeBillQuery(params);
            List<EmployeeMonthEntity> employeeMonthEntityList = new ArrayList<>();
            for(List<Object> receiveBillOrder : receiveBillOrderList){
                String fBillNo = (String)receiveBillOrder.get(0);//收款单单据编号
                String fDate = (String)receiveBillOrder.get(1);//回款日期
                String collectionDate = StringUtils.substringBefore(fDate,"T");
                String jobNum = (String)receiveBillOrder.get(2);//工号
                String fSbayDate = (String)receiveBillOrder.get(3);//结算所属期
                Double settlementAmount = (Double)receiveBillOrder.get(4);//结算金额
                Double collectionAmount = (Double)receiveBillOrder.get(5);//回款金额
                if(StringUtils.isNotEmpty(jobNum) && StringUtils.isNotEmpty(fSbayDate)){
                    System.out.println(fBillNo);
                    String employeeMonth = StringUtils.substringBefore(fSbayDate,"T");
                    EmployeeMonthEntity employeeMonthEntity = employeeMonthService.getByJobNumAndMonth(jobNum,DateUtils.parseDateToStr("yyyy-MM",new SimpleDateFormat("yyyy-MM-dd").parse(employeeMonth)));
                    if(employeeMonthEntity!=null){
                        employeeMonthEntity.setSettlementAmount(BigDecimal.valueOf(settlementAmount));
                        employeeMonthEntity.setCollectionAmount(BigDecimal.valueOf(collectionAmount));
                        employeeMonthEntity.setCollectionDate(DateUtils.parseDate(collectionDate));
                        employeeMonthEntityList.add(employeeMonthEntity);
                        employeeMonthService.caclPriceBySettlementAmount(employeeMonthEntity,BigDecimal.valueOf(settlementAmount));
                    }
                }
            }
            if(employeeMonthEntityList!=null && employeeMonthEntityList.size()>0){
                employeeMonthService.updateBatchById(employeeMonthEntityList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }


    public K3CloudApiClient login(){
        K3CloudApiClient client = new K3CloudApiClient("https://zhifei.ik3cloud.com/k3cloud/");
        Boolean login;
        try {
            login = client.login("1372529010512232448","administrator","zhifei123456@",2052);
            // 判断是否登录 如果登录成功 返回 对象 否则报异常
            if (login) {
                return client;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }


    public JSONObject FNumber(String fNumber){
        JSONObject transData = new JSONObject();
        transData.put("FNumber",fNumber);
        return transData;
    }

}
